<template>
    <div class="table" v-loading.body="loading">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-menu"></i>用户管理</el-breadcrumb-item>
<!--                 <el-breadcrumb-item>基础表格</el-breadcrumb-item> -->
            </el-breadcrumb>
        </div>
        <div class="handle-box">
            <el-button type="success" icon="plus" class="handle-del mr10" @click="create">添加用户</el-button>
            <el-input v-model="select_word" placeholder="搜索用户名" class="handle-input mr10"></el-input>
            <el-button type="primary" icon="search" @click="list">搜索</el-button>
        </div>
        <el-table :data="tableData" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange" >
<!--             <el-table-column type="selection" width="55"></el-table-column> -->
            <el-table-column prop="image" label="头像" width="150">
                <template scope="scope">
                    <img :src="scope.row.fullAvatar" class="round_image" v-show="scope.row.avatar!=''"/>
                </template>
            </el-table-column>
            <el-table-column prop="name" label="用户名">
            </el-table-column>
            <el-table-column prop="nickname" label="昵称">
            </el-table-column>
            <el-table-column prop="type" label="用户类型">
                <template scope="scope">
                    <el-tag type="success" v-if="scope.row.type==0">学生</el-tag>
                    <el-tag type="warning" v-if="scope.row.type==1">教师</el-tag>
                    <el-tag type="danger" v-if="scope.row.type==2">管理员</el-tag>
                </template>
            </el-table-column>
<!--             <el-table-column label="平均得分">
                <template scope="scope">
                    <el-tag type="success">{{scope.row.average_point}}</el-tag>
                </template>
            </el-table-column> -->
<!--             <el-table-column prop="hard_rate" label="难度">
                <template scope="scope">
                    <el-rate
						  v-model="scope.row.hard_rate"
						  disabled
							>
					</el-rate>
                </template>
            </el-table-column> -->

            <el-table-column label="操作">
                <template scope="scope">
                    <el-button size="small"
                            @click="edit(scope.$index, scope.row)">编辑</el-button>
<!--                     <el-button size="small" type="primary" @click="goto(scope.row)">管理题目</el-button> -->
                    <el-button size="small" type="danger" @click="del(scope.$index,scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
                    @current-change ="handleCurrentChange"
                    layout="prev, pager, next"
                    :current-page.sync="pagination.current"
                    :page-size="pagination.size"
                    :total="pagination.total">
            </el-pagination>
        </div>
        <div class="dialog">
            <el-dialog title="基本信息" :visible.sync="isadding">
              <el-form :model="user" :rules="rules" ref="ruleForm">
                <el-form-item label="头像" label-width="80px">
                    <el-upload
                      :disabled="user.avatar!=''"
                      class="upload-demo"
                      :action="uploadUrl"
                      :on-remove="handleRemoveAvatar"
                      list-type="picture-card"
                      :file-list="avatars"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <i class="el-icon-plus" ></i>
                      <div slot="tip" class="el-upload__tip">只能上传单张jpg/png/gif文件，且不超过8M</div>
                    </el-upload>
<!--                     <el-dialog size="tiny">
                      <img width="100%" :src="user.avatar" alt="">
                    </el-dialog> -->
                </el-form-item>
                <el-form-item label="用户名" label-width="80px" prop="name">
                  <el-input v-model="user.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="昵称" label-width="80px" prop="nickname">
                  <el-input v-model="user.nickname" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="" label-width="80px" v-show="user.id > 0">
                      <el-alert
                        title="密码置空,将不会更新密码"
                        type="warning"
                        close-text="知道了">
                      </el-alert>
                </el-form-item>
                <el-form-item label="登录密码" label-width="80px" prop="password">
                  <el-input v-model="user.password" auto-complete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" label-width="80px">
                  <el-input v-model="user.repassword" auto-complete="off" type="password"></el-input>
                </el-form-item>
                <el-form-item label="用户类型" label-width="80px" prop="type">
                  <el-select v-model="user.type" placeholder="请选择" size="180px" >
                    <el-option
                      v-for="item in user_type"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
                        <span>{{item.title}}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="考试分类" label-width="80px" prop="type">
<!--                   <el-tree
                      :data="test_categories"
                      :props="defaultProps"
                      node-key="id"
                      :expand-on-click-node="false"
                      :accordion="true"
                      >
                  </el-tree> -->
                    <el-select v-model="user.pq_test_category_id" placeholder="请选择" class="handle-select mr24">
                        <el-option
                          v-for="item in test_categories"
                          :key="item.id"
                          :label="item.title"
                          :value="item.id">
                            <span>{{item.prefix}}{{item.title}}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发布" label-width="80px" prop="state">
                	<el-radio class="radio" v-model="user.state" label="1">发布</el-radio>
					<el-radio class="radio" v-model="user.state" label="0">不发布</el-radio>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="isadding = false">取 消</el-button>
                <el-button type="primary" @click="save(true,'ruleForm')" v-show="user.id < 1">确 定</el-button>
                <el-button type="success" @click="save(false,'ruleForm')" v-show="user.id > 0">更 新</el-button>
              </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
    import http from "../../lib/http"
    import tree from "../../lib/tree"
    import "../../assets/main.css"
    export default {
        data : function() {
            return {
                fileList2 : [],
                //url: './static/vuetable.json',
                uploadUrl : http.base + '/users/avatar',
                isadding : false,
                loading : true,
                tableData: [],
                cur_page: 1,
                multipleSelection: [],
                avatars : [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                dataTotal : 0,
                rules: {
                    name: [
                        { required: true, message: '请输入用户名', trigger: 'blur' }
                    ],
                    password: [
                        { required: false, message: '请输入密码', trigger: 'blur' }
                    ]
                },
                user_type : [{
                    id : "0",title : "学生"
                },{
                    id : "1",title : "教师"
                },{
                    id : "2",title : "管理员"
                }],
                search : {
                    pq_test_category_id : "1",
                    user_type : "0"
                },
                user : {
                    id : '',
                    nickname : '',
                    name : "",
                    password : "",
                    type : "0",
                    state : '1',
                    avatar : ''
                },
                pagination : {
                    current : 1,
                    total : 0,
                    size : 20
                },
                defaultProps: {
                    children: 'children',
                    label: 'title'
                },
                test_categories : {},
            }
        },
        created : function(){
            var self = this
            http.alive(this,function(){
                self.list();
                self.getCategory();
            })
        },
        computed: {
            // tableData : function(){
            //     var self = this;
            //     // return self.tableData.filter(function(d){
            //     //     console.log(d)
            //     //     d.hard_rate  *= 1
            //     // })
            // }
        },
        methods: {
            handleRemoveAvatar : function(file, fileList) {
                this.user.avatar = ""
                this.avatars = []
            },
            handlePreview : function(file) {
                console.log(file);
            },
            handleAvatarSuccess : function(file){
                //console.log(file)
                this.user.avatar = file.msg
                //this.avatars = [{name:file.msg,url:"http://image.ipuqing.com/"+file.msg}]
            },
            beforeAvatarUpload : function(file){
                var isImg = false
                switch(file.type){
                    case 'image/png' :
                    case 'image/jpeg' : 
                    case 'image/jpg' : 
                    case 'image/gif' :
                        isImg = true
                    break;
                }
                if (!isImg) {
                    this.$message.error('只支持图片上传,其它文件不允许上传');
                }
                return isImg
            },
            initUser : function(){
                this.user = {
                    id : '',
                    nickname : '',
                    name : "",
                    password : "",
                    type : "0",
                    state : '1',
                    avatar : ''
                }
            },
            handleCurrentChange : function(val){
                this.cur_page = val;
                this.list();
            },
            getCategory : function(){
                var self = this;

                http.get(self,"test_categories").then((res) => {
                    var response = res.data
                    if (response.code == "ok") {
                        self.test_categories = tree.make(response.data,"pid",0)
                    }
                })
            },
            list : function(){
                var self = this;
                this.loading = true
                var params = {
                	skip : (this.pagination.current - 1) * this.pagination.size,
                	limit : this.pagination.size
                }
                http.get(self,"users",params).then((res) => {
                    var response = res.data
                    self.loading = false
                    if (response.code == "ok") {
                        if (!response.data) {
                            self.tableData = []
                            self.pagination.total = 0
                        }
                        else{
                            self.tableData = response.data
                            for(var i=0,j=self.tableData.length;i<j;i++){
                                if(self.tableData[i].avatar != ""){
                                    self.tableData[i].fullAvatar = 'http://image.ipuqing.com/'+(self.tableData[i].avatar)
                                }
                                //console.log()
                            }
                            self.pagination.total = response.total * 1
                        }
                    }
                })
            },
            categoryChange: function(){
                console.log(this.user.pq_test_category_id)
            },
            create : function(){
                this.isadding = true
                this.initUser()
                this.avatars = []
                //this.user.pq_test_category_id = this.test_categories[0].id
            },
            save : function(add,form){
                var self = this
                self.$refs[form].validate(function(valid){
                    if(valid){
                        console.log(self.user)
                        http.post(self,"users",self.user).then((res)=>{
                            self.isadding = false
                            var data = res.data
                            if (data.code == "ok") {
                                self.$notify.success({
                                    title : '成功',
                                    message : '保存成功'
                                })
                                self.list()                        
                            }
                            else{
                                self.$notify.error({
                                    title : "错误",
                                    message : data.msg
                                })
                            }
                        })
                    }
                })

            },
            formatter : function(row, column) {
                return row.address;
            },
            goto : function(row){
                location.href = '#/user-'+row.id
            },
            // filterTag : function(value, row) {
            //     return row.tag === value;
            // },
            edit : function(index, user) {
                this.isadding = true
                this.user = JSON.parse(JSON.stringify(user))
                this.user.password = ''
                // this.search.user_type = this.user.type
                // this.search.pq_test_category_id = this.user.pq_test_category_id
                // console.log(this.user)
                if (this.user.avatar != "") {
                    this.avatars = [{
                        name : this.user.avatar,url:'http://image.ipuqing.com/'+this.user.avatar
                    }]
                }
                else{
                    this.avatars = []
                }
            },
            del : function(index, row) {
                var self = this
                this.$confirm('此操作将删除此用户,确定删除吗?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                    http.delete(this,"users/"+row.id).then(function(res){
                        self.list()
                    })
                }).catch(() => {
     
                });
            },
            handleSelectionChange : function(val) {
                this.multipleSelection = val;
            }
        }
    }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
  .round_image{
    width: 50px;
    height:50px;
    border-radius:25px;
    border : 1px solid #ccc;
  }
</style>
